from flask import jsonify
from config.config import mysqlConfig
from database.connectorMysq import DatabaseUtils
from model.tools import compareUserTokens

db_utils = DatabaseUtils(
    pool_name='admin',
    host=mysqlConfig["host"],
    user=mysqlConfig["user"],
    password=mysqlConfig["password"],
    database=mysqlConfig["database"]
)


def addNavlist(userid, url, img, category, navname, token):
    try:
        with db_utils.get_connection() as connection:
            if not compareUserTokens(connection, userid, token):
                return {"msg": "token已经过期，请重新获取"}

            query = "INSERT INTO navlist (category, navname, url, img) VALUES (%s, %s, %s, %s)"
            data = (category, navname, url, img)

            with connection.cursor() as cursor:
                cursor.execute(query, data)
                connection.commit()

            return {"msg": "增加成功"}
    except Exception as e:
        print(e)
        return {"msg": "增加失败，请稍后重试"}


def getNavlist(userid, token):
    try:
        with db_utils.get_connection() as connection:
            if not compareUserTokens(connection, userid, token):
                return {"msg": "token已经过期，请重新获取"}

            query = "SELECT * FROM navlist;"
            with connection.cursor() as cursor:
                cursor.execute(query)
                data = cursor.fetchall()

            jsons = [{
                "id": item[0],
                "category": item[1],
                "name": item[2],
                "url": item[3],
                "img": item[4],
            } for item in data]

            return jsonify(jsons)
    except Exception as e:
        print(e)
        return "获取失败"


def delNavlist(userid, navid, token):
    try:
        with db_utils.get_connection() as connection:
            if not compareUserTokens(connection, userid, token):
                return {"msg": "token已经过期，请重新获取"}

            query = "DELETE FROM navlist WHERE id = %s"
            data = (navid,)

            with connection.cursor() as cursor:
                cursor.execute(query, data)
                connection.commit()

            return "删除成功"
    except Exception as e:
        print(e)
        return "删除未成功"
